package com.itheima.tliasproject.interceptor;

import com.itheima.tliasproject.utils.CurrentHolder;
import com.itheima.tliasproject.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 获取请求路径
        String uri = request.getRequestURI();
        log.info("拦截到请求：{}", uri);

        // 获取令牌
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            log.warn("请求头token为空，拒绝访问");
            return sendError(response, HttpStatus.SC_UNAUTHORIZED, "未登录，请先登录");
        }

        // 解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer userId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(userId); // 存储用户ID
            log.info("令牌解析成功，当前用户ID：{}", userId);
        } catch (ExpiredJwtException e) {
            log.error("令牌已过期：{}", e.getMessage());
            return sendError(response, HttpStatus.SC_UNAUTHORIZED, "令牌已过期，请重新登录");
        } catch (SignatureException e) {
            log.error("令牌签名错误：{}", e.getMessage());
            return sendError(response, HttpStatus.SC_UNAUTHORIZED, "令牌无效");
        } catch (Exception e) {
            log.error("令牌解析失败：{}", e.getMessage());
            return sendError(response, HttpStatus.SC_UNAUTHORIZED, "未登录，请先登录");
        }

        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHolder.remove(); // 清理线程本地变量
        log.info("请求处理完成，清除当前用户信息");
    }

    // 封装错误响应
    private boolean sendError(HttpServletResponse response, int status, String msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(status);
        response.getWriter().write("{\"code\":" + status + ",\"msg\":\"" + msg + "\"}");
        return false;
    }
}